package com.example.xmpic.ui.activity.setting;

import android.os.Message;
import android.view.View;
import android.widget.SeekBar;

import com.basic.G;
import com.example.common.base.BaseBindActivity;
import com.example.xmpic.R;
import com.example.xmpic.databinding.ActivitySettingExpertBinding;
import com.example.xmpic.support.FunError;
import com.example.xmpic.support.FunLog;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.OnFunDeviceOptListener;
import com.example.xmpic.support.config.CloudStorage;
import com.example.xmpic.support.config.JsonConfig;
import com.example.xmpic.support.config.RecordParam;
import com.example.xmpic.support.config.RecordParamEx;
import com.example.xmpic.support.config.SimplifyEncode;
import com.example.xmpic.support.config.SystemInfo;
import com.example.xmpic.support.models.FunDevType;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.utils.DeviceConfigType;
import com.example.xmpic.support.utils.MyUtils;
import com.example.xmpic.ui.adapter.OptionAdapter;
import com.lib.EUIMSG;
import com.lib.FunSDK;
import com.lib.IFunSDKResult;
import com.lib.JSONCONFIG;
import com.lib.MsgContent;
import com.lib.SDKCONST;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @author skygge
 * @date 2019-11-25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：摄像头高级设置页面
 */
public class CameraSetExpertActivity extends BaseBindActivity<ActivitySettingExpertBinding> implements OnFunDeviceOptListener, IFunSDKResult {

    private FunDevice mFunDevice = null;

    /**
     * 本界面需要获取到的设备配置信息
     */
    private String[] DEV_CONFIGS_FOR_CAMARA = {
            // 获取参数:SimplifyEncode -> audioEable
            SimplifyEncode.CONFIG_NAME,

            // 获取参数:RecordParam
            RecordParam.CONFIG_NAME,

            RecordParamEx.CONFIG_NAME,

            // 获取参数:CloudStorage
            // CloudStorage.CONFIG_NAME
    };

    private final String[] DEV_CONFIGS_FOR_CHANNELS = {
            // 获取参数:RecordParam
            RecordParam.CONFIG_NAME,
    };

    private String[] DEV_CONFIGS = DEV_CONFIGS_FOR_CHANNELS;
    // 设置配置信息的时候,由于有多个,通过下面的列表来判断是否所有的配置都设置完成了
    private final List<String> mSettingConfigs = new ArrayList<>();

    private String[] item;
    private ArrayList<String> items;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting_expert;
    }

    @Override
    protected void initialize() {
        super.initialize();

        int devId = getIntent().getIntExtra("FUN_DEVICE_ID", 0);
        FunDevice funDevice = FunSupport.getInstance().findDeviceById(devId);
        if ( null == funDevice ) {
            finish();
            return;
        }

        mFunDevice = funDevice;
    }

    @Override
    protected void initView() {
        super.initView();
        items = new ArrayList<>();
        // 注册设备操作监听
        FunSupport.getInstance().registerOnFunDeviceOptListener(this);
        SystemInfo info = (SystemInfo) mFunDevice.getConfig(SystemInfo.CONFIG_NAME);
        if (info != null && info.getVideoInChannel() > mFunDevice.CurrChannel) {
            // 获取是否支持主辅码流录像
            int useId = FunSDK.RegUser(this);
            FunSDK.DevGetConfigByJson(useId, mFunDevice.getDevSn(), JSONCONFIG.SUPPORT_EXTRECORD, 4096, -1, 5000, 0);
        } else {
            DEV_CONFIGS = DEV_CONFIGS_FOR_CHANNELS;
            // 获取报警配置信息
            tryGetRecordConfig();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        item = getResources().getStringArray(R.array.device_setup_camera_definition_values);
        items.addAll(Arrays.asList(item));
        mDBind.setDefinition.setAdapter(new OptionAdapter(items, 150));
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivExpertBack.setOnClickListener(view -> finish());
        mDBind.tvSaveVideo.setOnClickListener(view -> trySaveRecordConfig());
        mDBind.openVideo.setOnClickListener(view -> view.setSelected(!view.isSelected()));
        mDBind.openAudio.setOnClickListener(view -> view.setSelected(!view.isSelected()));
        mDBind.videoSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b){
                    mDBind.videoTime.setText(i + getString(R.string.device_setup_record_minute));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mDBind.videoDefinition.setOnClickListener(view -> {
            mDBind.videoShow.setVisibility(View.VISIBLE);
        });
        mDBind.tvSave.setOnClickListener(view -> {
            mDBind.videoShow.setVisibility(View.GONE);
            mDBind.videoDefinition.setDetailText(item[mDBind.setDefinition.getCurrentItem()]);
        });
        mDBind.tvCancel.setOnClickListener(view -> mDBind.videoShow.setVisibility(View.GONE));
    }

    private void tryGetRecordConfig() {
        if ( null != mFunDevice ) {
            showProgressDialog();
            for ( String configName : DEV_CONFIGS ) {

                // 删除老的配置信息
                mFunDevice.invalidConfig(configName);

                if(mFunDevice.getDevType() == FunDevType.EE_DEV_SMALLEYE || configName != CloudStorage.CONFIG_NAME)
                {
                    // 重新搜索新的配置信息
                    if (contains(DeviceConfigType.DeviceConfigCommon, configName)) {
                        FunSupport.getInstance().requestDeviceConfig(mFunDevice,
                                configName);
                    }else if (contains(DeviceConfigType.DeviceConfigByChannel, configName)) {
                        FunSupport.getInstance().requestDeviceConfig(mFunDevice, configName, mFunDevice.CurrChannel);
                    }
                }
            }
        }
    }

    private void refreshRecordConfig() {
        SimplifyEncode simplifyEncode = (SimplifyEncode)mFunDevice.getConfig(SimplifyEncode.CONFIG_NAME);
        if ( null != simplifyEncode ) {
            mDBind.openAudio.setSelected(simplifyEncode.mainFormat.AudioEnable);
            // 清晰度
            int current = -(simplifyEncode.mainFormat.video.Quality-6);
            mDBind.videoDefinition.setDetailText(item[current]);
            mDBind.setDefinition.setCurrentItem(current);
        }

        RecordParam recordParam = (RecordParam)mFunDevice.getConfig(RecordParam.CONFIG_NAME);
        if ( null != recordParam ) {

            mDBind.videoTime.setText(recordParam.getPacketLength() + getString(R.string.device_setup_record_minute));
            mDBind.videoSeekBar.setProgress(recordParam.getPacketLength());

            if(getIntRecordMode(recordParam.getRecordMode()) == 2)
            {
                boolean bNormalRecord = MyUtils.getIntFromHex(recordParam.mask[0][0]) == 7;
                FunLog.i("setup record", "TTT--->" + recordParam.recordMode + "bNormalRecord" + (bNormalRecord ? 1 : 2));
                mDBind.openVideo.setSelected(!bNormalRecord);
            }
            else
            {
                mDBind.openVideo.setSelected(getIntRecordMode(recordParam.getRecordMode()) == 2);
            }
        }
    }

    private void trySaveRecordConfig() {
        boolean beSimplifyEncodeChanged = false;
        SimplifyEncode simplifyEncode = (SimplifyEncode)mFunDevice.getConfig(SimplifyEncode.CONFIG_NAME);
        if ( null != simplifyEncode ) {
            if ( simplifyEncode.mainFormat.AudioEnable != mDBind.openAudio.isSelected() ) {
                simplifyEncode.mainFormat.AudioEnable = mDBind.openAudio.isSelected();
                beSimplifyEncodeChanged = true;
            }
            // 清晰度
            if (simplifyEncode.mainFormat.video.Quality != -(mDBind.setDefinition.getCurrentItem()-6)) {
                simplifyEncode.mainFormat.video.Quality = -(mDBind.setDefinition.getCurrentItem()-6);
                beSimplifyEncodeChanged = true;
            }
        }

        boolean beRecordParamChanged = false;
        RecordParam recordParam = (RecordParam)mFunDevice.getConfig(RecordParam.CONFIG_NAME);
        if ( null != recordParam )
        {

            if(mDBind.videoSeekBar.getProgress() != recordParam.getPacketLength())
            {
                recordParam.setPacketLength(mDBind.videoSeekBar.getProgress());
            }

            int mode = mDBind.openVideo.isSelected() ? 2 : 1;

//			if(!getStringRecordMode(mode).equals(recordParam.getRecordMode()))
//			{
            recordParam.recordMode = getStringRecordMode(mode == 1 ? 2 : mode);
            // 如果是联动配置的话，把普通录像去掉
            for (int i = 0; i < SDKCONST.NET_N_WEEKS; ++i) {
                recordParam.mask[i][0] = MyUtils.getHexFromInt(mode == 2 ? 6 : 7);
            }
            beRecordParamChanged = true;
//			}
        }
        showProgressDialog();

        // 保存SimplifyEncode
        if ( beSimplifyEncodeChanged ) {
            synchronized (mSettingConfigs) {
                mSettingConfigs.add(simplifyEncode.getConfigName());
            }

            FunSupport.getInstance().requestDeviceSetConfig(mFunDevice, simplifyEncode);
        }

        if ( beRecordParamChanged ) {
            synchronized (mSettingConfigs) {
                mSettingConfigs.add(recordParam.getConfigName());
            }

            FunSupport.getInstance().requestDeviceSetConfig(mFunDevice, recordParam);
        }
    }

    private boolean isCurrentUsefulConfig(String configName) {
        for ( int i = 0; i < DEV_CONFIGS.length; i ++ ) {
            if ( DEV_CONFIGS[i].equals(configName) ) {
                return true;
            }
        }
        return false;
    }

    private int getIntRecordMode(String s) {
        if (s.equals("ClosedRecord")) {
            return 0;
        } else if (s.equals("ManualRecord")) {
            return 1;
        } else {
            return 2;
        }
    }

    private String getStringRecordMode(int i) {
        if (i == 0) {
            return "ClosedRecord";
        } else if (i == 1) {
            return "ManualRecord";
        } else {
            return "ConfigRecord";
        }
    }

    /**
     * 判断是否所有需要的配置都获取到了
     * @return
     */
    private boolean isAllConfigGetted() {
        for ( String configName : DEV_CONFIGS ) {
            if ( null == mFunDevice.getConfig(configName) ) {
                if(mFunDevice.getDevType() == FunDevType.EE_DEV_SMALLEYE || configName != CloudStorage.CONFIG_NAME)
                {
                    return false;
                }
            }
        }
        return true;
    }
    /**
     *  判断某个字符串是否存在于数组中
     *  用来判断该配置是否通道相关
     *  @param stringArray 原数组
     *  @param source 查找的字符串
     *  @return 是否找到
     */
    private boolean contains(String[] stringArray, String source) {
        // 转换为list
        List<String> tempList = Arrays.asList(stringArray);

        // 利用list的包含方法,进行判断
        return tempList.contains(source);
    }
    @Override
    public void onDeviceLoginSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceLoginFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceGetConfigSuccess(FunDevice funDevice, String configName, int nSeq) {
        if ( null != mFunDevice && funDevice.getId() == mFunDevice.getId() && isCurrentUsefulConfig(configName) ) {
            if ( isAllConfigGetted() ) {
                dismissProgressDialog();
            }
            refreshRecordConfig();
        }
    }

    @Override
    public void onDeviceGetConfigFailed(FunDevice funDevice, Integer errCode) {
        showToast(FunError.getErrorStr(errCode));
    }

    @Override
    public void onDeviceSetConfigSuccess(FunDevice funDevice, String configName) {
        if ( null != mFunDevice
                && funDevice.getId() == mFunDevice.getId() ) {
            synchronized (mSettingConfigs) {
                mSettingConfigs.remove(configName);
                if ( mSettingConfigs.size() == 0 ) {
                    dismissProgressDialog();
                    showToast(getString(R.string.success));
                    finish();
                }
            }
        }
    }

    @Override
    public void onDeviceSetConfigFailed(FunDevice funDevice, String configName, Integer errCode) {
        showToast(FunError.getErrorStr(errCode));
    }

    @Override
    public void onDeviceChangeInfoSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceChangeInfoFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceOptionSuccess(FunDevice funDevice, String option) {

    }

    @Override
    public void onDeviceOptionFailed(FunDevice funDevice, String option, Integer errCode) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice, H264_DVR_FILE_DATA[] datas) {

    }

    @Override
    public void onDeviceFileListGetFailed(FunDevice funDevice) {

    }

    @Override
    public int OnFunSDKResult(Message message, MsgContent msgContent) {
        if (message.what == EUIMSG.DEV_GET_JSON) {
            if (JsonConfig.SUPPORT_EXTRECORD.equals(msgContent.str)) {
                if (message.arg1 > 0) {
                    try {
                        JSONObject jsonObject = new JSONObject(G.ToString(msgContent.pData));
                        if (jsonObject.has(JsonConfig.SUPPORT_EXTRECORD)) {
                            JSONObject object = jsonObject.getJSONObject(JsonConfig.SUPPORT_EXTRECORD);
                            if (object.has("AbilityPram")) {
                                String ability = object.getString("AbilityPram");
                                // AbilityPram  0支持主码流录像，1支持辅码流录像，2都支持
                                if ("0".equals(ability) || "0x00000000".equals(ability)) {
                                    DEV_CONFIGS_FOR_CAMARA = new String[]{
                                            // 获取参数:SimplifyEncode -> audioEable
                                            SimplifyEncode.CONFIG_NAME,
                                            // 获取参数:RecordParam
                                            RecordParam.CONFIG_NAME,
                                    };
                                } else if ("1".equals(ability) || "0x00000001".equals(ability)) {
                                    DEV_CONFIGS_FOR_CAMARA = new String[] {
                                            // 获取参数:SimplifyEncode -> audioEable
                                            SimplifyEncode.CONFIG_NAME,
                                            RecordParamEx.CONFIG_NAME,
                                    };
                                } else if ("2".equals(ability) || "0x00000002".equals(ability)) {
                                    DEV_CONFIGS_FOR_CAMARA = new String[] {
                                            // 获取参数:SimplifyEncode -> audioEable
                                            SimplifyEncode.CONFIG_NAME,
                                            // 获取参数:RecordParam
                                            RecordParam.CONFIG_NAME,
                                            RecordParamEx.CONFIG_NAME,
                                    };
                                }
                                DEV_CONFIGS = DEV_CONFIGS_FOR_CAMARA;
                                // 获取报警配置信息
                                tryGetRecordConfig();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    showToast(FunError.getErrorStr(message.arg1));
                }
            }
        }
        return 0;
    }

    @Override
    protected void onDestroy() {

        // 注销监听
        FunSupport.getInstance().removeOnFunDeviceOptListener(this);

        super.onDestroy();
    }

}
